package ran.quzitech.rnble.utils;

import android.util.Log;

public class DataUtil {
    private static final String TAG = "DataUtil";

    public static byte[] hexToByteArray(String hexStr)
            throws NumberFormatException {
        if ((hexStr == null) || (hexStr.length() == 0))
            return null;
        if (hexStr.length() % 2 == 1) {
            hexStr = String.valueOf(0) + hexStr;
        }
        String[] subStrs = new String[hexStr.length() / 2];
        byte[] result = new byte[subStrs.length];
        for (int i = 0; i < subStrs.length; i++) {
            subStrs[i] = hexStr.substring(2 * i, 2 * (i + 1));
            result[i] = (byte) Integer.parseInt(subStrs[i], 16);
        }
        return result;
    }

    public static byte[] hexToReversedByteArray(String hexStr) {
        if ((hexStr == null) || (hexStr.length() == 0))
            return null;
        if (hexStr.length() % 2 == 1) {
            hexStr = String.valueOf(0) + hexStr;
        }
        String[] subStrs = new String[hexStr.length() / 2];
        byte[] result = new byte[subStrs.length];
        for (int i = 0; i < subStrs.length; i++) {
            subStrs[i] = hexStr.substring(2 * (subStrs.length - 1 - i),
                    2 * (subStrs.length - i));
            try {
                result[i] = (byte) Integer.parseInt(subStrs[i], 16);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static String byteArrayToHex(byte[] data) {
        if ((data == null) || (data.length == 0))
            return "";
        StringBuilder builder = new StringBuilder(data.length);
        for (int i = 0; i < data.length; i++) {
            builder.append(String.format("%02X ",
                    new Object[]{Byte.valueOf(data[i])}));
        }
        return builder.toString();
    }

    public static String byteToBinaryString(byte b) {
        StringBuilder sb = new StringBuilder(8);
        for (int i = 7; i > -1; i--) {
            sb.append(bit(b, i));
        }
        Log.d("DataUtil", "byteToBinaryString() - " + b + ": " + sb.toString());
        return sb.toString();
    }

    private static int bit(int src, int bitIndex)
            throws IllegalArgumentException {
        if (bitIndex < 0)
            throw new IllegalArgumentException("bitIndex must >= 0");
        int result = src >> bitIndex & 0x1;
        return result;
    }
}